package com.mktech.taraservice.http.customvolleyrequest;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mktech.taralib.entity.login.LoginBean;
import com.mktech.taralib.util.LogTool;

public class LoginBeanRequest extends Request<LoginBean>
{
	private Listener<LoginBean> mListener;
	private Map<String, String> map;
	
	public LoginBeanRequest(int method, String url, Listener<LoginBean> listener, ErrorListener errorListener)
	{
		super(method, url, errorListener);
		mListener = listener;
	}

	public LoginBeanRequest(String url, Listener<LoginBean> listener, ErrorListener errorListener)
	{
		this(Method.GET, url, listener, errorListener);
	}

	public void setPostParams(Map<String, String> params)
	{
		map = params;
	}
	
	@Override
	protected void deliverResponse(LoginBean response)
	{
		// TODO Auto-generated method stub
		mListener.onResponse(response);
	}

	@Override
	protected Response<LoginBean> parseNetworkResponse(NetworkResponse response)
	{
		// TODO Auto-generated method stub
		try
		{
			String string = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
			LogTool.i(string);
			Gson gson = new Gson();
			Type type = new TypeToken<LoginBean>(){}.getType();
			return Response.success((LoginBean)gson.fromJson(string, type), HttpHeaderParser.parseCacheHeaders(response));
		}
		catch (UnsupportedEncodingException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Response.error(new ParseError(e));
		}
		return null;
	}
	
	@Override
	protected Map<String, String> getParams() throws AuthFailureError
	{
		// TODO Auto-generated method stub
		return map;
	}
	
}
